package com.iknight.mgr.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Service;

import com.iknight.mgr.api.CommonService;

@Service
public class CommonServiceImpl implements CommonService {

	@Override
	public void postMailToRecp(String mailHost, String protocolType, String masterUser, String masterAuthCode,
			String[] recipients, String mailTitle, String mailContent) {
		// TODO Auto-generated method stub

		Properties props = new Properties();

		props.setProperty("mail.transport.protocol", protocolType);
		props.setProperty("mail.smtp.auth", "true");

		Session session = Session.getDefaultInstance(props);
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(masterUser, "邮箱注册服务中心"));
			List<InternetAddress> addresses = new ArrayList<>();
			for (String address : recipients) {
				addresses.add(new InternetAddress(address));
			}
			message.setRecipients(MimeMessage.RecipientType.TO,
                    addresses.toArray(new InternetAddress[addresses.size()]));
            // message.setRecipient(MimeMessage.RecipientType.TO, new
			// InternetAddress(recipients[0], recipients[0]));

			message.setSubject(mailTitle, "UTF-8");
			message.setContent(mailContent, "text/html;charset=UTF-8");
			message.setSentDate(new Date());
			message.saveChanges();
			Transport transport = session.getTransport();
			// transport.connect(masterUser, masterAuthCode);
			transport.connect(mailHost, 25, masterUser, masterAuthCode);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (UnsupportedEncodingException | MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
